const path = require('path');
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 每次打包之前，自动删除文件夹
const cleanWebpackPlugin = require('clean-webpack-plugin')



let WEBPACK_ENV = process.env.WEBPACK_ENV || 'dev'
console.log(WEBPACK_ENV)
module.exports = {
	entry: {
		// 项目代码入口
		app: path.join(__dirname, './src/app.jsx'),
		// 第三方包入口
		vendor: ['react', 'react-router', 'antd', 'react-addons-pure-render-mixin', 'react-dom', 'react-router-dom']
	},
	output: {
		path: path.resolve(__dirname, './dist'),
		publicPath: WEBPACK_ENV === 'dev' ? '/dist/' : '/',
		//filename: 'js/app.js'

		// 此处的name由 entry 中的属性名决定
		// chunk 表示一个代码块（webpack模块化分析代码后的结构）
		filename: 'js/[name].[chunkhash].js',
		// ------添加 chunkFilename, 指定输出js文件的名称------
		chunkFilename: 'js/[name].[chunkhash].js'

	},
	resolve: {
		alias: {
			page: path.resolve(__dirname, 'src/page'),
			component: path.resolve(__dirname, 'src/component'),
			util: path.resolve(__dirname, 'src/util'),
			service: path.resolve(__dirname, 'src/service'),
			img: path.resolve(__dirname, 'src/img')
		}
	},
	module: {
		rules: [{
			test: /\.jsx$/,
			use: {
				loader: 'babel-loader',
				options: {
					presets: ['env', 'react', 'es2015']
				}
			}
		}, {
			test: /\.css$/,
			use: ExtractTextPlugin.extract({
				fallback: "style-loader",
				use: "css-loader"
			})
		}, {
			test: /\.scss$/,
			use: ExtractTextPlugin.extract({
				fallback: 'style-loader',
				//如果需要，可以在 sass-loader 之前将 resolve-url-loader 链接进来
				use: ['css-loader', 'sass-loader']
			})
		}, {
			test: /\.(png|jpg|gif)$/,
			use: [{
				loader: 'url-loader',
				options: {
					limit: 8192,
					name: 'img/[hash:8].[name].[ext]'
				}
			}]
		}, {
			test: /\.(woff|woff2|svg|eot|ttf|otf)$/,
			use: [{
				loader: 'url-loader',
				options: {
					limit: 8192,
					name: 'resource/[name].[ext]'
				}
			}]
		}]
	},
	devServer: {
		//contentBase: './dist'
		port: 8808,
		historyApiFallback: {
			index: '/dist/index.html'
		},
		proxy: {
			'/user': {
				target: 'http://rap2api.taobao.org/app/mock/7483/POST',
				changeOrigin: true //伪装成target地址发送
			},
			'/base': {
				target: 'http://rap2api.taobao.org/app/mock/7483/GET',
				changeOrigin: true //伪装成target地址发送
			}
		}
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: './src/index.html',
			favicon: './favicon.ico'

		}),
		// 自动删除dist目录
		// 参数：表示要删除文件的路径，可以是多个
		new cleanWebpackPlugin(['./dist']),

		// 通过插件抽离 css (参数)
		// 参数：表示将抽离的css文件生成到哪个目录中
		new ExtractTextPlugin("css/[name].css"),

		//提出公共模块
		new webpack.optimize.CommonsChunkPlugin({
			name: 'vendor',
			filename: 'js/base.js'
		})
	]
};